package com.fanshuai.soring.boot.config;

import com.fanshuai.soring.boot.web.LogFilter;
import com.fanshuai.soring.boot.web.MyServlet1;
import com.fanshuai.soring.boot.web.MyServlet2;
import com.google.common.collect.ImmutableList;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableAsync
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public ServletRegistrationBean<MyServlet1> servletRegistration1() {
        ServletRegistrationBean<MyServlet1> registrationBean = new ServletRegistrationBean<>(new MyServlet1());
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/servlet1");
        registrationBean.setName("servlet1");

        return registrationBean;
    }

    @Bean
    public ServletRegistrationBean<MyServlet2> servletRegistration2() {
        ServletRegistrationBean<MyServlet2> registrationBean = new ServletRegistrationBean<>(new MyServlet2());
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/servlet2");
        registrationBean.setName("servlet2");

        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<LogFilter> filterRegistration1() {
        FilterRegistrationBean<LogFilter> registrationBean = new FilterRegistrationBean<>(new LogFilter());
        registrationBean.setName("LogFilter");
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        registrationBean.setServletNames(ImmutableList.of("servlet1", "servlet2"));

        return registrationBean;
    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(1200 * 1000L);
        //configurer.setTaskExecutor(taskExecutor());
    }

    @Bean
    public SimpleAsyncTaskExecutor taskExecutor() {
        SimpleAsyncTaskExecutor executor = new SimpleAsyncTaskExecutor();
        executor.setConcurrencyLimit(Runtime.getRuntime().availableProcessors());
        executor.setThreadNamePrefix("asyncTaskExecutor-");

        return executor;
    }
}
